package com.cdy.client.handler;

import com.cdy.client.FileUploadClient;
import com.cdy.client.netty.NettyClient;
import com.cdy.common.command.UploadCommand;
import com.cdy.common.response.Response;
import com.cdy.common.response.UploadResponse;
import com.cdy.common.uitl.FileUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import static com.cdy.client.netty.NettyClient.NETTY_CLIENT;


/**
 * 上传响应处理器
 * <p>
 * Created by 陈东一
 * 2019/10/20 0020 12:36
 */
@Slf4j
public class UploadResponseHandler implements ResponseHandler {

    @Override
    public void handle(ChannelHandlerContext ctx, Response msg)  {
        UploadResponse uploadResponse = (UploadResponse) msg;
        Boolean finish = uploadResponse.getComplete();
        if (finish) {
            FileUploadClient.isFinish = true;
            return;
        }
        Boolean success = uploadResponse.getSuccess();
        if (!success) {
            UploadCommand upload = new UploadCommand();
            upload.setBegin(uploadResponse.getBegin());
            NettyClient nettyClient = ctx.channel().attr(NETTY_CLIENT).get();
            upload.setClientId(nettyClient.getCommonProperty().getClientId());
            upload.setSectionId(uploadResponse.getSectionId());
            upload.setSectionBegin(uploadResponse.getSectionBegin());
            upload.setBitBegin(uploadResponse.getBitBegin());
            upload.setBitSize(uploadResponse.getBitSize());
            upload.setFileMD5(FileUploadClient.md5);
            ByteBuf byteBuf =null;
            try {
                byteBuf = FileUtil.readChannel(FileUploadClient.channel, upload.getBegin(), Math.toIntExact(upload.getLength()));
                upload.setByteBuf(byteBuf);
                upload.setLength((long) byteBuf.capacity());
                FileUploadClient.queue.add(upload);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                if (byteBuf!=null) {
                    byteBuf.release();
                }
            }

        }
    }
}
